import config from '../config'
import jwt from 'jsonwebtoken'
const { jwt_config } = config
/* 验证token模块 */
export const token = (req, res, next) => {
  // split(' ')通过空格对字符串进行切割，返回一个数组
  // pop()删除数组的第一个值
  let token = String(req.headers.authorization).split(' ').pop()
  //   token =
  //     'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwODgzOTUxOTk1NmI5NTBiMGI2YmE5NiIsInVzZXJuYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6IiQyYiQxMCQzSGR5c2FDWUswU3pmOTMuNTh2L2IuSUlsRU5INjZRMTRDbzl0NndFVEswYy9TQ2k5UFZhMiIsImlhdCI6MTYyODE1NzU2MiwiZXhwIjoxNjI4MjQzOTYyfQ.xhz9SPCRbQ6iuVRhJBbLqW418-VK1fRzaY-50QM6oqs'
  jwt.verify(
    token,
    jwt_config.secretKey,
    jwt_config.expiresIn,
    (err, result) => {
      // token校验不通过
      if (err) return res.sendResult(500, err.message, null)
      // token校验成功
      console.log('测试result:', result)
      if (!result) return res.sendResult(500, 'token已失效', null)
      req.result = result
      next()
    }
  )
}
